package com.osfw.framework.web.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.StpUtil;
import com.antherd.smcrypto.sm2.Sm2;
import com.google.code.kaptcha.Constants;
import com.osfw.framework.config.VerifyCodeGenerator;
import com.osfw.framework.core.controller.BaseController;
import com.osfw.framework.utils.CookieUtils;
import com.osfw.framework.utils.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 图片验证码（支持算术形式）
 */
@Controller
@RequestMapping("/osfw/captcha")
public class CaptchaController extends BaseController {

    /**
     * 获取验证码图片
     *
     * @param response
     * @param request
     */
    @SaIgnore
    @GetMapping("/captchaImage")
    public void getCaptchaImage(HttpServletResponse response, HttpServletRequest request) {
        ServletOutputStream out = null;
        try {
            response.setDateHeader("Expires", 0);
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            response.setHeader("Pragma", "no-cache");
            response.setContentType("image/jpeg");

            int width = 300;
            int height = 140;
            BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            //生成对应宽高的初始图片
            String code = VerifyCodeGenerator.drawRandomText(width, height, bi);
            StpUtil.getTokenSessionByToken(CookieUtils.getCookie(request, com.osfw.framework.constants.Constants.TEMP_TOKEN_NAME)).set(Constants.KAPTCHA_SESSION_KEY, code);

            out = response.getOutputStream();
            ImageIO.write(bi, "jpg", out);
            out.flush();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 验证验证码
     *
     * @param imgCode
     * @param request
     */
    @PostMapping("/checkCaptchaCode")
    @ResponseBody
    public Boolean checkCaptchaCode(String imgCode, HttpServletRequest request) {
        String privateKey = StpUtil.getTokenSessionByToken(CookieUtils.getCookie(request, com.osfw.framework.constants.Constants.TEMP_TOKEN_NAME)).get("privateKey").toString();
        imgCode = Sm2.doDecrypt(imgCode, privateKey);
        String code = StpUtil.getTokenSessionByToken(CookieUtils.getCookie(request, com.osfw.framework.constants.Constants.TEMP_TOKEN_NAME)).getString(Constants.KAPTCHA_SESSION_KEY);
        if (StringUtils.isEmpty(imgCode) || !imgCode.equalsIgnoreCase(code)) {
            // 验证码清除，防止多次使用。
            StpUtil.getTokenSessionByToken(CookieUtils.getCookie(request, com.osfw.framework.constants.Constants.TEMP_TOKEN_NAME)).delete(Constants.KAPTCHA_SESSION_KEY);
            return false;
        }
        return true;
    }

}